package com.spring.hx.util;

import com.spring.hx.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {
    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean exists( String key) {
        Boolean hasKey = redisTemplate.hasKey(key);
        return hasKey!=null&& hasKey;
    }
    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    public void remove(String key) {
        redisTemplate.delete(key);
    }
    /**
     * 普通缓存获取
     */
    public Object get(String key) {
        return key==null?null:redisTemplate.opsForValue().get(key);
    }
    /**
     * 普通缓存放入
     */
     public void set(String key, User userInfo, int time) {
        redisTemplate.opsForValue().set(key,userInfo,time,TimeUnit.SECONDS);
    }
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time   时间(秒)
     */
    public boolean setExpireTime(String key, int time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 根据key 获取过期时间
     * @param key  键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire==null?0:expire;
    }
}
